package com.njwb.day14.dao.swing;

import javax.swing.*;
import java.awt.*;

public class LoginUI {
    public static void main(String[] args) {
        JFrame frame = new JFrame("登录");
        frame.setSize(300, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5,5,5,5);

        // 用户名
        gbc.gridx = 0;
        gbc.gridy = 0;
        frame.add(new JLabel("用户名:"), gbc);

        gbc.gridx = 1;
        JTextField userText = new JTextField(15);
        frame.add(userText, gbc);

        // 密码
        gbc.gridx = 0;
        gbc.gridy = 1;
        frame.add(new JLabel("密码:"), gbc);

        gbc.gridx = 1;
        JPasswordField passwordText = new JPasswordField(15);
        frame.add(passwordText, gbc);

        // 登录按钮
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.CENTER;
        JButton loginButton = new JButton("登录");
        frame.add(loginButton, gbc);

        // 点击登录
        loginButton.addActionListener(e -> {
            String username = userText.getText();
            String password = new String(passwordText.getPassword());

            StudentService service = new StudentService();
            try {
                if (service.login(username, password)) {
                    JOptionPane.showMessageDialog(frame, "登录成功！");
                    frame.dispose();
                    new StudentView().show();
                } else {
                    JOptionPane.showMessageDialog(frame, "用户名或密码错误！");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(frame, "数据库错误！");
            }
        });

        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
